package com.cyj.springbootservice.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;

/**
 * @description: RestTemplate
 * @Author C_Y_J
 * @create 2021-03-22 10:29
 **/
@Configuration
@Slf4j
public class RestTemplateConfig {

//    @Bean
//    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
//        RestTemplate restTemplate = new RestTemplate(factory);
//        // 支持中文编码
//        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
//        return restTemplate;
//    }

//    @Bean
//    public RestTemplate restTemplate(ClientHttpRequestFactory httpRequestFactory) {
//
//        RestTemplate restTemplate = new RestTemplate();
//        /**
//         * StringHttpMessageConverter 默认使用ISO-8859-1编码，此处修改为UTF-8
//         */
//        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
//        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
//        while (iterator.hasNext()) {
//            HttpMessageConverter<?> converter = iterator.next();
//            if (converter instanceof StringHttpMessageConverter) {
//                ((StringHttpMessageConverter) converter).setDefaultCharset(Charset.forName("UTF-8"));
//            }
//        }
//
//        //Interceptors 添加写的 Interceptors
//        restTemplate.setInterceptors(Lists.newArrayList(
//                new LogClientHttpRequestInterceptor()));
//        //BufferingClientHttpRequestFactory  此处替换为BufferingClientHttpRequestFactory
//        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(httpRequestFactory));
//        return restTemplate;
//    }

    /**
     * https://blog.csdn.net/qq_41430638/article/details/115512670
     *
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //将RequestFactory换成BufferingClientHttpRequestFactory方便从流中获取调用结果
        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
        //日志打印
        restTemplate.getInterceptors().add((httpRequest, bytes, clientHttpRequestExecution) -> {
            log.info("URL:{}", httpRequest.getURI().toString());
            log.info("METHOD:{}", httpRequest.getMethodValue());
            log.info("PARAMS:{}", new String(bytes));
            ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
            try (ByteArrayOutputStream ops = new ByteArrayOutputStream()) {
                StreamUtils.copy(response.getBody(), ops);
                log.info("RESULT:{}", ops.toString());
            } catch (Exception e) {
                log.error("复制流异常", e);
            }
            return response;

        });
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //单位为ms
        factory.setReadTimeout(5000);
        //单位为ms
        factory.setConnectTimeout(5000);
        return factory;
    }
}
